﻿using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace iTool.Validator
{
    public class ValidatorUtils
    {
        /// <summary>
        /// 根据方法获取缓存关键字
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string GetMethodCacheKeyByMethod(MethodInfo method)
        {
            string cacheKey = method.Name;

            foreach (var item in method.GetParameters())
            {
                cacheKey += $"_{item.Name}_{item.ParameterType.Name}";
            }

            return cacheKey;
        }

        /// <summary>
        /// 根据控制器获取缓存关键字
        /// </summary>
        /// <param name="actin"></param>
        /// <returns></returns>
        public static string GetMethodCacheKeyByControllerActionDescriptor(ActionDescriptor actin)
        {
            var actionInfo = (ControllerActionDescriptor)actin;

            string cacheKey = actionInfo.ActionName;

            foreach (var item in actin.Parameters)
            {
                cacheKey += $"_{item.Name}_{item.ParameterType.Name}";
            }

            return cacheKey;
        }

        /// <summary>
        /// 根据ActionArguments来构造反射调用需要的参数
        /// </summary>
        /// <param name="ActionArguments"></param>
        /// <returns></returns>
        public static object[] GetMethodParameterByActionArguments(IDictionary<string, object> ActionArguments)
        {
            var obj = new object[ActionArguments.Count];

            int index = 0; foreach (var item in ActionArguments)
            {
                obj[index] = item.Value;
                index++;
            }

            return obj;
        }

        /// <summary>
        /// 查看方法是否不再过滤名单
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public static bool GetMethodIsNotFilterList(MethodInfo method)
        {
            /// 创建字典时过滤的方法名称
            string[] filterMethodNames = new string[] { "OnActionExecuting", "OnActionExecuted", "ValidatorError", "Equals", "GetHashCode", "get_TypeId", "Match", "IsDefaultAttribute", "ToString", "GetType" };
            return !filterMethodNames.Contains(method.Name);
        }



    }
}
